<?php
/**
 * @author GhostWei
 * @date Sep 29, 2012
 */
class translator_api_baidu extends translator_abstract {
	
	protected $_url = 'http://translate.baidu.com/transcontent';
	
	public function translate() {
		$response = new translator_response();
		try {
			$concept = $this->getConcept('baidu');
		} catch (Exception $e) {
			return $response->setError($e->getMessage());
		}
		$params = array(
				'from' => $this->getFrom(),
				'token' => $concept->getAppKey(),
				'ie' => 'data',
				't' => time() . rand(100, 999),
				'to' => $this->getTo(),
				'source' => 'txt',
				'query' => $this->getText()
		);
		$data = $this->parseJson($this->post($this->_url, $params));
		if(!isset($data->data) || !is_array($data->data)) {
			return $response->setError('undefined translation from response json');
		}
		if(isset($data->status) && $data->status != 0) {
			return $response->setError('error code: ' . $data->status);
		}
		if(!isset($data->data[0])) {
			return $response->setResult($this->getText());
		}
		$data = $data->data[0];
		if(!isset($data->dst)) {
			return $response->setError('undefined index dst');
		}
		return $response->setResult($data->dst);
	}
	
	protected function parseJson($data) {
		try {
			$json = @json_decode($data);
		} catch (Exception $e) {
			return new stdClass();
		}
		return is_object($json) ? $json : new stdClass();
	}
	
}

